package com.sctvcloud.bazhong.ui.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;

import com.luck.picture.lib.tools.PictureFileUtils;

import org.xutils.common.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

import wseemann.media.FFmpegMediaMetadataRetriever;

public class UIUtils {
    private static float density = 1.0f;
    private static int screenWidth;
    private static int screenHeight;
    private static long lastClick;

    public static int dpToPx(Resources res, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                res.getDisplayMetrics());
    }

    public static float getDensity() {
        return density;
    }

    public static int getScreenWidth() {
        return screenWidth;
    }

    public static int getScreenHeight() {
        return screenHeight;
    }

    public static void initDisplayMetrics(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrics);
        density = metrics.density;
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;

    }

    // 用于控制快速连续点击事件只触发一次
    public static boolean fastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClick < 500) {
            return true;
        }
        lastClick = time;
        return false;
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    public static int dip2px(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    /**
     * px转换dip
     */
    public static int px2dip(Context context, int px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * px转换sp
     */
    public static int px2sp(Context context, int pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * sp转换px
     */
    public static int sp2px(Context context, int spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取sd位置
     */
    public static String getSDPath() {
        String sdExtra = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(sdExtra)) {
            return sdExtra;
        }
        sdExtra = Environment.getExternalStorageDirectory().getAbsolutePath();
        if (!TextUtils.isEmpty(sdExtra)) {
            return sdExtra;
        }
        sdExtra = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(System.getenv(sdExtra))) {
            return sdExtra;
        }
        return null;
    }

    /**
     * 数字处理
     * @param count
     * @return
     */
    public static String getNumber(long count) {
        if(count>10000) {
            double num = (double) count / 10000;
            return new DecimalFormat("0.00").format(num) + "万";
        }else{
            return ""+count;
        }
    }

    /**
     * 阅读--数字处理
     *
     * @param count
     * @return
     */
    public static String getReadingNumber(long count) {
//        if (count > 1000000) {
//            return "100万+阅读";
//        } else if (count == 1000000) {
//            return "100万阅读";
//        } else {
//            if (count > 10000) {
//                //1万到100万之间
//                double num = (double) count / 10000;
////                DecimalFormat df=new DecimalFormat(".0");
////                String st=df.format(num);
//                BigDecimal b = new BigDecimal(num);
//                BigDecimal a = b.setScale(1, BigDecimal.ROUND_DOWN);
//                return a.toString() + "万阅读";
//            } else if (count > 0) {
//                return "" + count + "阅读";
//            }else{
//                return "0阅读";
//            }
//        }

        return "";
    }

    public static String getDomain(String url) {
        String result = "";
        if(!TextUtils.isEmpty(url)) {
            int j = 0, startIndex = 0, endIndex = 0;
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/') {
                    j++;
                    if (j == 2)
                        startIndex = i;
                    else if (j == 3)
                        endIndex = i;
                }

            }
            result = url.substring(0, endIndex);
        }
        return result;
    }

    /**
     * 判断程序的运行在前台还是后台
     *
     * @param context
     * @return 0在未运行  大于0在运行
     */
    public static int isBackground(Context context) {
        try {
            ActivityManager activityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> listInfos = activityManager
                    .getRunningTasks(20);
            // 判断程序是否在栈顶
            if (listInfos.get(0).baseActivity.getClassName().equals("com.sctvcloud.bazhong.ui.activities.SplashActivity")) {
                LogUtil.d("isBackground--正在运行 前台2");
                return 2;
            }else if (listInfos.get(0).topActivity.getPackageName().equals(context.getPackageName())) {
                LogUtil.d("isBackground--正在运行 前台1");
                return 1;
            } else {
//                // 判断程序是否在栈里
//                for (ActivityManager.RunningTaskInfo info : listInfos) {
//                    if (info.topActivity.getPackageName().equals(context.getPackageName())) {
//                        LogUtil.d("isBackground---正在运行 后台");
//                        return 1;
//                    }
//                }
                LogUtil.d("isBackground--未运行");
                return 0;// 栈里找不到，返回3
            }
        } catch (Exception e) {
            LogUtil.d("isBackground--未运行");
            return 0;
        }

    }

    /**
     * 获取视频封面图片
     * @param videoPath 视频资源路径
     * @return 视屏封面图片路径
     */
    public static  String getFirstFrameFromVideo(String videoPath) {
        FFmpegMediaMetadataRetriever media;
        Bitmap bitmap;
        try {
            // 获取视频的缩略图
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND); //調用ThumbnailUtils類的靜態方法createVideoThumbnail獲取視頻的截圖；
            if (bitmap == null) {
                media = new FFmpegMediaMetadataRetriever();
                media.setDataSource(videoPath);
                bitmap = media.getFrameAtTime(100, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                if (bitmap == null) {
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        try {
            //当文件未创建时，先创建文件夹。之后再创建图片文件
            String path = Environment.getExternalStorageDirectory().getPath() + PictureFileUtils.CAMERA_PIC_PATH;
            File fileNew = new File(path);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }
            File file = new File(fileNew, "CoverCut_" + System
                    .currentTimeMillis() + ".jpeg");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
